function [G1,cc,impact,fmat,fwt,ywt,gev,eu]=amasolve(a0,a1,a2,cc,psi,uprbnd,condn)
%========================================================================== 
% AMASOLVE.m 
%
% Inputs: 
% A0*E[y(t+1)|t]+ A1*y(t) = A2*y(t-1) + PSI*e(t) 
%
% 
% NOTE: A2 is on the right hand side!!!! 
%       Pass -A2 as an input if using the more standard notation 
%
% A0*E[y(t+1)|t]+ A1*y(t) + A2*y(t-1) = PSI*e(t) % 
%
% UPRBND    upper bound allowed for unit roots, similar to DIV in
%           gensys
% CONDN     Zero tolerance used as a condition number test
%           by numeric_shift and reduced_form
% If not defined will be set to their default values 
%
% Outputs
% -------
% Same as Gensys solution 
% y(t)=G1*y(t-1)+C+R*z(t)+ywt*inv(I-fmat*inv(L))*fwt*z(t+1) 
%
% Note: In gensys GEV=[A B] and compute the roots as B./A 
% AMA returns only a subset of the roots so to make output comparable 
% will report an artificial variable GEV=[Aama Bama] 
% where Bama has in the first K rows the roots returned by AMA 
% and zeros in the next (NY-NK) rows, while A is an NY x 1 column of 1s
%
% Alejandro Justiniano
% Adapted from Gary Anderson's GENSYStoAMA matlab code. 
% Changed sorting of output by AIMCODE values to guarantee output is
% produced
% July 9th 2007 
% =========================================================================
if nargin < 7
    condn=1.e-10;
    if nargin < 6
        uprbnd =1+1.e-6;%allow unit roots
    end
end
ny=size(a1,1); 
% 1. Call SPAMAlg that implements AMA
% -----------------------------------
[G1,rts,~,~,~,~,aimcode]=feval(@SPAmalg,sparse([-a2 a1 a0]),size(a1,1),1,1,condn,uprbnd);
if aimcode > 5
    G1=[];
    CC=[];
    impact=[];
    ywt=[];
    fmat=[];
    fwt=[];
    gev=[];
    eu=[0;0]; 
    return;
end
eu=setEu(aimcode);
eu=eu(:);
ywt=[];
fmat=[];
fwt=[];
if isequal(eu,[1;1]);
    impact=((a1+a0*sparse(G1))\eye(ny))*psi;
    gev=[ones(ny,1) [rts;ones(ny-length(rts),1)]];
else
    impact=[];
    gev=[]; 
end
% ======================================
% Solution indicator same as Gensys 
% =======================================
function euVal=setEu(aimCode)
euVal=zeros(1,2);
switch aimCode
    case 1
        euVal(1,1)=1;
        euVal(1,2)=1;
    case 2
        euVal(1,1)=-2;
        euVal(1,2)=-2;
        %disp('Coincident Zeros');
    case 3
        euVal(1,1)=0;
        euVal(1,2)=0;
        %disp('No solution'); 
    case 4
        euVal(1,1)=1;
        euVal(1,2)=0;
        %disp('Indeterminacy'); 
    case 5
        euVal(1,1)=-5;
        euVal(1,2)=-5;
end